package com.itzmn.newcode.offer1;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/19 13:58
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 反转链表
 *
 *  输入一个链表，反转链表后，输出新链表的表头。
 *
 *  头插法，反转链表
 *
 */
public class _15_ReverseList {

    public static void main(String[] args) {
        new _15_ReverseList().test();
    }

    private void test() {

        ListNode listNode = initListNode();
        ReverseList(listNode);

    }

    public ListNode ReverseList(ListNode head) {
        if (head == null){
            return null;
        }

        // 头插法

        ListNode tempHead = head;
        head = head.next;
        tempHead.next = null;

        while (head!=null){

            ListNode temp = head;
            // 将下个节点设为头
            head = head.next;

            // 将头的插入到以前的链表
            temp.next = tempHead;
            tempHead = temp;

        }

        logLinkedList(tempHead);
        return tempHead;
    }

    private void logLinkedList(ListNode head){
        while (head!=null){
            System.out.println(head.val+" ");
            head = head.next;
        }
        System.out.println();
    }
    /**
     * 初始化链表
     * @return
     */
    public ListNode initListNode(){

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        return listNode1;
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }


}
